package com.linkstec.base.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.linkstec.base.constant.SysConstant;
import com.linkstec.base.service.WechatTokenManageService;
import com.linkstec.base.util.HttpClientUtil;
import com.linkstec.base.util.PropUtil;
import com.linkstec.base.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WechatTokenManageServiceImpl implements WechatTokenManageService {

	Logger logger = LoggerFactory.getLogger(WechatTokenManageServiceImpl.class);

	@Autowired
	RedisUtil redisUtil;
	@Autowired
	PropUtil propUtil;

	/**
	 * 获取员工token
	 * @return
	 */
	@Override
	public String getUserToken() {
		String token = (String) redisUtil.get(SysConstant.base_redis_user_token_key);
		if (StringUtils.isEmpty(token)) {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("corpid", propUtil.prop_qywechat_corpid);
			jsonObject.put("corpsecret", propUtil.prop_qywechat_user_corpsecret);
			token = getToken(jsonObject);
			if (token != null) {
				redisUtil.set(SysConstant.base_redis_user_token_key, token, SysConstant.base_redis_time);
			} else {
				throw new RuntimeException("token获取失败!");
			}
		}
		return token;
	}

	/**
	 * 获取客户token
	 * @return
	 */
	@Override
	public String getCustomerToken() {
		String token = (String) redisUtil.get(SysConstant.base_redis_customer_token_key);
		if (StringUtils.isEmpty(token)) {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("corpid", propUtil.prop_qywechat_corpid);
			jsonObject.put("corpsecret", propUtil.prop_qywechat_customer_corpsecret);
			token = getToken(jsonObject);
			if (token != null) {
				redisUtil.set(SysConstant.base_redis_customer_token_key, token, SysConstant.base_redis_time);
			} else {
				throw new RuntimeException("token获取失败!");
			}
		}
		return token;
	}

	public String getToken(JSONObject jsonObject) {
		String token = HttpClientUtil.sendGet(propUtil.prop_qywechat_qyapi_url + propUtil.prop_qywechat_gettoken_url, jsonObject);
		if (!StringUtils.isEmpty(token)) {
			JSONObject data = JSONObject.parseObject(token);
			if (data != null) {
				return data.getString("access_token");
			} else {
				logger.error("token为空，jsonObject={}", jsonObject);
			}
		} else {
			logger.error("token获取失败，jsonObject={}", jsonObject);
		}
		return null;
	}

}
